package com.duck.base.oauth.security.handler;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.duck.base.oauth.jwt.JWTUtils;
import com.duck.base.oauth.security.model.DuckUserDetails;
import com.duck.base.oauth.security.model.TokenModel;
import com.duck.base.response.BaseResponse;

/**
 * 登录成功返回的 JSON 格式数据
 * @author lwy
 *
 */
@Component
public class DuckAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private JWTUtils jwtUtils;
    
    @Value("${jwt.access_token.expiration}")
    private Long access_token_expiration;
    
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {
		// TODO Auto-generated method stub
		DuckUserDetails userDetails = (DuckUserDetails) authentication.getPrincipal();
		BaseResponse<TokenModel> baseResp = new BaseResponse<TokenModel>();
		TokenModel model = new TokenModel();
		model.setToken(jwtUtils.generateAccessToken(userDetails));
		model.setRefresh_token(jwtUtils.generateRefreshToken(userDetails));
		model.setExpires(access_token_expiration);
		baseResp.setData(model);
		response.getWriter().write(JSON.toJSONString(baseResp));
	}

}
